package com.xinchao.service.impl;

import com.xinchao.dao.DeviceAdvertisementMapper;
import com.xinchao.exception.ServiceException;
import com.xinchao.model.DeviceAdvertisement;
import com.xinchao.service.DeviceAdvertisementService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author dxy
 * @date 2018/11/6 17:59
 */
@Service(value = "deviceAdvertisementService")
public class DeviceAdvertisementServiceImpl implements DeviceAdvertisementService {
	@Autowired
	private DeviceAdvertisementMapper deviceAdvertisementMapper;

	/**
	 * 保存终端
	 *
	 * @param deviceAdvertisement 终端广告
	 * @throws ServiceException
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveDeviceAdvertisement(DeviceAdvertisement deviceAdvertisement) throws ServiceException {
		if (deviceAdvertisement == null) {
			throw new ServiceException("输入参数不能为空");
		}
		deviceAdvertisementMapper.insertDeviceAdvertisement(deviceAdvertisement);
	}

	/**
	 * 通过机器码修改终端广告
	 *
	 * @param deviceAdvertisement DeviceAdvertisement
	 * @throws ServiceException
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateDeviceAdvertisementByDeviceNumber(DeviceAdvertisement deviceAdvertisement) throws ServiceException {
		if (deviceAdvertisement == null) {
			throw new ServiceException("输入参数不能为空");
		}
		deviceAdvertisementMapper.updateDeviceAdvertisementByDeviceNumber(deviceAdvertisement);
	}

	/**
	 * 报告已下载广告数量
	 *
	 * @param deviceAdvertisement DeviceAdvertisement
	 * @throws ServiceException
	 */
	@Override
	public void reportDownloadedAdvertisementNum(DeviceAdvertisement deviceAdvertisement) throws ServiceException {
		if (deviceAdvertisement == null) {
			throw new ServiceException("输入参数不能为空");
		}
		String deviceNumber = deviceAdvertisement.getDeviceNumber();
		//通过机器码获取终端广告
		DeviceAdvertisement oldDeviceAdvertisment = getDeviceAdvertisementByDeviceNumber(deviceNumber);
		//如果数据不存在，就保存新数据
		if (oldDeviceAdvertisment == null) {
			deviceAdvertisementMapper.insertDeviceAdvertisement(deviceAdvertisement);
		} else {
			//如果存在就修改数据
			deviceAdvertisementMapper.updateDeviceAdvertisementByDeviceNumber(deviceAdvertisement);
		}
	}

	/**
	 * 通过机器码获取终端广告
	 *
	 * @param deviceNumber 机器码
	 * @return DeviceAdvertisement
	 * @throws ServiceException
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public DeviceAdvertisement getDeviceAdvertisementByDeviceNumber(String deviceNumber) throws ServiceException {
		if (StringUtils.isBlank(deviceNumber)) {
			throw new ServiceException("输入参数不能为空");
		}
		return deviceAdvertisementMapper.getDeviceAdvertisementByDeviceNumber(deviceNumber);
	}
}
